import { ref } from 'vue'
import {
	defineStore
} from 'pinia'
import { login, getUserinfo } from '@/api/index'
import { UserInfo } from '@/types/index'
import { LoginParam } from '@/types/api.ts'

export const useUserStore = defineStore('user', () => {
	/**
	 * 服务供应商
	 */
	const provider = ref<string>('')
	/**
	 * 登录信息
	 */
	const loginInfo = ref({
		app_id: '',
		token: ''
	})
	/**
	 * 用户信息
	 */
	const userInfo = ref<UserInfo>(null)
	/**
	 * 登录参数
	 */
	const loginParam = ref<LoginParam>({
		link_id: '',
		official_account_id: '',
		uid: '',
		mobile_system: ''

		// #ifdef MP-WEIXIN
		, clickid: '',
		advertiser_id: '',
		ip: '',
		ua: '',
		type: ''
		// #endif
	})

	const Login = async (cellback ?: Function) => {
		// #ifdef MP-KUAISHOU
		const info = ks.getAccountInfoSync()
		loginInfo.value.app_id = info.miniProgram.appId
		// #endif
		if (!loginInfo.value.app_id) {
			// #ifdef MP-TOUTIAO
			const info = tt.getEnvInfoSync()
			loginInfo.value.app_id = info.microapp.appId
			// #endif

			// #ifdef MP-WEIXIN
			const info = uni.getAccountInfoSync()
			loginInfo.value.app_id = info.miniProgram.appId

			// #endif

			// #ifdef MP-KUAISHOU
			const info = ks.getAccountInfoSync()
			loginInfo.value.app_id = info.miniProgram.appId
			// #endif
		}

		uni.login({
			provider: provider.value,
			success: async (_res : UniApp.LoginRes) => {
				try {
					const registerResponse = Object.assign(loginInfo.value, await login({
						code: _res.code,
						app_id: loginInfo.value.app_id,
						...loginParam.value
					}) || {})

					console.log(registerResponse)
					const app = getApp();
					if (app.sdk) {
						//设置opneid，必须先设置openid再上报注册行为。setopenId为同步方法，设置完可立即上报注册行为。
						app.sdk.setOpenId(registerResponse.open_id);
						if (registerResponse.track == 1) {
							//上报注册行为，后台接口判断是否为注册用户

							app.sdk.track('REGISTER');
							console.log('注册')
						}

					}



					cellback()
				} catch (e) {
					console.log(e.message)
					//TODO handle the exception
				}
			}
		})
	}

	const GetUserinfo = async () => {
		try {
			userInfo.value = await getUserinfo() || {}
		} catch (e) {
			//TODO handle the exception
		}
	}

	return { provider, loginInfo, userInfo, loginParam, Login, GetUserinfo }
}, {
	persist: {
		storage: {
			setItem(key, value) {
				uni.setStorageSync(key, value)
			},
			getItem(key) {
				return uni.getStorageSync(key)
			}
		}
	}
})